package superminer.xinfang.com.ipreport.util.netty;

import android.util.Log;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * 编码
 * Created by Administrator on 2018/3/22.
 */

public class NewEncoder extends MessageToByteEncoder<Message> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Message message, ByteBuf byteBuf) throws Exception {
        if(message == null){
            throw new Exception("未获得消息内容");
        }

        int mt=message.getType();
        String data=message.getMsgBody();
        //与后台协议好，如何设置校验部分，然后和json一起发给服务器
        byte[] bytes = data.getBytes();

        int head = 0xff << 22 | (bytes.length + 1);
        byte[] headbyte = intToBytes2(head);
        byte[] allByte = new byte[bytes.length + headbyte.length + 1];
        Log.i("-->", "NewEncoder：" + mt + "  " + data + " " + allByte.length);
        System.arraycopy(headbyte, 0, allByte, 0, headbyte.length);

        System.arraycopy(new byte[]{(byte) mt}, 0, allByte, headbyte.length, 1);
        System.arraycopy(bytes, 0, allByte, headbyte.length + 1, bytes.length);
        byteBuf.writeBytes(allByte);


    }

    /**
     * int转为byte数组
     *
     * @param value
     * @return
     */
    public byte[] intToBytes2(int value) {
        byte[] src = new byte[4];
        src[3] = (byte) ((value >> 24) & 0xFF);
        src[2] = (byte) ((value >> 16) & 0xFF);
        src[1] = (byte) ((value >> 8) & 0xFF);
        src[0] = (byte) (value & 0xFF);
        return src;
    }
}
